package action.newelifile;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import action.adapter.FtpFileAdapter;
import action.adapter.FtpItemServerAdapter;
import action.adapter.LANServerAdapter;
import action.pojo.LANConnect;
import action.pojo.LocalFilePojo;
import action.util.LANConnectSQLITE;
import action.util.LoadSetting;
import action.util.Tool;
import action.util.UsersDAO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class LanActivity extends Activity {
	Button expandButton,addressButton,switchButton,backButton,changeViewButton,uploadButton,sortButton,multiButton,mBackButton,
	mCopyButton,mCutButton,mDeleteButton,mCancelButton;
	ImageView imageView1,imageView2,imageMobile,imageSdcard;
	GridView gridView;
	ListView listView,listDetailView;
	TextView txtViewEmpty;
	
	LinearLayout expandLayout;
	Dialog dialog;
	
	// create server lan
	LANConnectSQLITE lanConnectSQLITE;
	ArrayList<LANConnect> lstLANServer;
	LANServerAdapter adapterServerLAN;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		try{
		LoadSetting.load(this);
		initLocale();
		setContentView(R.layout.main);
		LoadSetting.loadTheme(this);
		
		lanConnectSQLITE = new LANConnectSQLITE(this);
//		lanConnectSQLITE.open();
		
		Tool.position = 2;
		initAttribute();
		
		initData();
		
		processButton();
		super.onCreate(savedInstanceState);
		}catch (Exception e) {
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
	
	public void initLocale(){
		String languageToLoad = Tool.locale(LoadSetting.setting.getLanguage());  
	    Locale locale = new Locale(languageToLoad);   
	    Locale.setDefault(locale);  
	    Configuration config = new Configuration();  
	    config.locale = locale;  
	    getBaseContext().getResources().updateConfiguration(config,   
	    getBaseContext().getResources().getDisplayMetrics());  
	}
	
	public void initAttribute(){
		expandButton = (Button)findViewById(R.id.expandButton);
		addressButton = (Button)findViewById(R.id.addressButton);
		switchButton = (Button)findViewById(R.id.switchButton);
		backButton = (Button)findViewById(R.id.backButton);
		changeViewButton = (Button)findViewById(R.id.changeViewButton);
		uploadButton = (Button)findViewById(R.id.uploadButton);
		sortButton = (Button)findViewById(R.id.sortButton);
		multiButton = (Button)findViewById(R.id.multiButton);
		mBackButton = (Button)findViewById(R.id.mBackButton);
		mCopyButton = (Button)findViewById(R.id.mCopyButton);
		mCutButton = (Button)findViewById(R.id.mCutButton);
		mDeleteButton = (Button)findViewById(R.id.mDeleteButton);
		mCancelButton = (Button)findViewById(R.id.mCancelButton);
		
		imageView1 = (ImageView)findViewById(R.id.imageView1);
		imageView2 = (ImageView)findViewById(R.id.imageView2);
		imageMobile = (ImageView)findViewById(R.id.imageMobile);
		imageSdcard = (ImageView)findViewById(R.id.imageSdcard);
		
		gridView = (GridView)findViewById(R.id.gridView);
		
		listView = (ListView)findViewById(R.id.listView);
		listDetailView = (ListView)findViewById(R.id.listDetailView);
		
		txtViewEmpty = (TextView)findViewById(R.id.txtViewEmpty);
		
		expandLayout = (LinearLayout)findViewById(R.id.expandLayout);
		
		imageSdcard.setImageResource(R.drawable.lan);
		switchButton.setText("LAN");
	}
	
	// init data 
	
	public void initData(){
		if(Tool.lan_path!= null && Tool.lan_path.size() > 0){
			
		}else{
			addressButton.setText(R.string.choose_machine);
			lstLANServer = new ArrayList<LANConnect>();
			refreshServerLAN();
		}
	}
	
	public void refreshServerLAN(){
		if (Tool.lan_path.size() == 0) {
			expandButton.setClickable(false);
			expandButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null,null);
			addressButton.setClickable(false);
		} else {
			expandButton.setClickable(true);
		}
		loadAllServerLAN();
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			initalGridView();
			break;
		case 1:
			initalListView();
			break;
		case 2:
			initalDetailView();
			break;
		default:
			break;
		}
	}
	
	// load all Server LAn
	public void loadAllServerLAN(){
		lanConnectSQLITE.open();
		lstLANServer = (ArrayList<LANConnect>)lanConnectSQLITE.getAllLANConnect();
		lanConnectSQLITE.close();
	}
	
	private void initalListView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.VISIBLE);
		listDetailView.setVisibility(ListView.GONE);
		txtViewEmpty.setVisibility(TextView.GONE);
		if(Tool.ftp_path.size()==0 && lstLANServer.size()>0){
			adapterServerLAN = new LANServerAdapter(LanActivity.this, R.layout.list_view, lstLANServer);
			listView.setAdapter(adapterServerLAN);
//			listView.setOnItemClickListener(onListFileClick());
//			listView.setOnItemLongClickListener(itemLongClick());
		}
		else{
			System.out.println(" vao day khong the");
			listView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}

	private void initalGridView() {
		gridView.setVisibility(GridView.VISIBLE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.GONE);
		txtViewEmpty.setVisibility(TextView.GONE);
		if(Tool.lan_path.size()==0 && lstLANServer.size()>0){
			adapterServerLAN = new LANServerAdapter(LanActivity.this, R.layout.grid_detail, lstLANServer);
			gridView.setAdapter(adapterServerLAN);
//			gridView.setOnItemClickListener(onListFileClick());
//			gridView.setOnItemLongClickListener(itemLongClick());
		}
		else{
			System.out.println(" vao day khong the");
			gridView.setVisibility(GridView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}

	private void initalDetailView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.VISIBLE);
		txtViewEmpty.setVisibility(TextView.GONE);

		if(Tool.lan_path!=null && Tool.lan_path.size()==0 && lstLANServer.size()>0){
			adapterServerLAN = new LANServerAdapter(LanActivity.this, R.layout.list_detail, lstLANServer);
			listDetailView.setAdapter(adapterServerLAN);
//			listDetailView.setOnItemClickListener(onListFileClick());
//			listDetailView.setOnItemLongClickListener(itemLongClick());
		}
		else{
			System.out.println(" vao day khong the");
			listDetailView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}
	
	// process button
	public void processButton(){
		expandButton.setOnClickListener(processButtonExpand());
		backButton.setOnClickListener(processButtonBack());
		addressButton.setOnClickListener(processButtonAddress());
		switchButton.setOnClickListener(processSwitchButton());
		changeViewButton.setOnClickListener(processChangeViewButton());
	}
	// process button expand
	public OnClickListener processButtonExpand(){
		OnClickListener onclick = new  View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(expandLayout.getVisibility()==LinearLayout.GONE){
					expandLayout.setVisibility(LinearLayout.VISIBLE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.subtract), null,null);
				}else{
					expandLayout.setVisibility(LinearLayout.GONE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.plus), null,null);
				}
			}
		};
		return onclick;
	}
	
	// process button back
	public OnClickListener processButtonBack(){
		OnClickListener action = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			}
		};
		return action;
	}
	
	// process button address
	public OnClickListener processButtonAddress(){
		OnClickListener onclick = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Tool.list_favorite = getFavorite();
				Intent intent = new Intent(getApplicationContext(), AddressActivity.class);
				startActivity(intent);
			}
		};
		return onclick;
	}
	
	// process change view button
	public OnClickListener processChangeViewButton(){
		OnClickListener listener = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {
					String[] list = new String[] {getResources().getString(R.string.girdview),getResources().getString(R.string.listview), 
							getResources().getString(R.string.detailview) };
					dialog = new Dialog(LanActivity.this);
					dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
					dialog.setContentView(R.layout.popup_switch);
					((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.changeView);
					ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
					listview.setAdapter(new ArrayAdapter<String>(LanActivity.this,R.layout.list_option,list));
					listview.setOnItemClickListener(changeViewClick());
					((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

						public void onClick(View v) {
							dialog.dismiss();
						}
					});
					dialog.setCanceledOnTouchOutside(true);
					dialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		
		return listener;
	}
	private OnItemClickListener changeViewClick(){
		OnItemClickListener action =new  OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2==0) {
					LoadSetting.setting.setDisplay(0);
				}
				if (arg2==1) {
					LoadSetting.setting.setDisplay(1);
				}
				if (arg2==2) {
					LoadSetting.setting.setDisplay(2);
				}
				UsersDAO user  = new UsersDAO(LanActivity.this);
				user.saveData(LoadSetting.setting.getBackground(), LoadSetting.setting.getDisplay(), LoadSetting.setting.getLanguage(), LoadSetting.setting.getIcon());
//				refreshItemServerFTP(Tool.connect);
				dialog.dismiss();
			}
		};
		return action;
	}
	
	private ArrayList<LocalFilePojo> getFavorite() {
		Tool.list_favorite = new ArrayList<LocalFilePojo>();
		
		return Tool.list_favorite;
	}
	
	
	private OnClickListener processSwitchButton() {
		OnClickListener action = new OnClickListener() {
			
			public void onClick(View v) {
				String[] list = new String[] { "Local", "LAN", "FTP" };
				dialog = new Dialog(LanActivity.this);
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
				dialog.setContentView(R.layout.popup_switch);
				((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.switch_to);
				ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
				listview.setAdapter(new ArrayAdapter<String>(LanActivity.this,
						android.R.layout.select_dialog_singlechoice, list));
				listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listview.setItemChecked(1, true);
				listview.setOnItemClickListener(switchToClick());
				((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					
					
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		};
		return action;
	}
	private OnItemClickListener switchToClick() {
		OnItemClickListener action = new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = null;
				if (arg2==0){
					 intent = new Intent(LanActivity.this,LocalActivity.class);
					 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				}else if (arg2==1){
					dialog.dismiss();
					return;
				}else if (arg2==2){
					intent  = new Intent(LanActivity.this,FtpActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				}
				dialog.dismiss();
				startActivity(intent);
				finish();
			}
		};
		return action;
	}
	
	// menu option
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_lan, menu);
		setMenuBackground();
		return super.onCreateOptionsMenu(menu);
	}

	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  

			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.color.menu_option_background);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_setting:
			Intent intent = new Intent(LanActivity.this,SettingActivity.class);
			startActivity(intent);
			break;
		case R.id.menu_new:
			if(Tool.lan_path.size()==0){
				processNewLANPopup();
			}else{
				processNewFolderItemLAN();
			}
			break;
		case R.id.menu_refresh:
			if(Tool.ftp_path.size()==0){
				refreshServerLAN();
			}else{
			}
			Toast.makeText(this, getString(R.string.reload), Toast.LENGTH_SHORT).show();
			break;
		case R.id.menu_quit:
			runExit();
			break;
		}
		return true;
	}

	private void runExit(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.exitapp));
		builder.setMessage(getString(R.string.questionexitapp));
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				LanActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
	
	// TODO process new LAN popup
	public void processNewLANPopup(){
		try {
			String[] list = {"New Server","Scan machine"};
			dialog = new Dialog(this);
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			dialog.setContentView(R.layout.popup_switch);
			((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.option);
			ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
			listview.setAdapter(new ArrayAdapter<String>(this,R.layout.list_option,list));
			listview.setOnItemClickListener(processItemClick());
			((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// process item click to create server or scan machine
	public OnItemClickListener processItemClick(){
		OnItemClickListener clickListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int position,
					long arg3) {
				switch (position) {
				case 0:
					createIPLAN();
					break;
				case 1:
					break;
				default:
					break;
				}
			}
		};
		return clickListener;
	}
	
	// TODO create IP LAN
	public void createIPLAN(){
		dialog = new Dialog(LanActivity.this);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		dialog.setContentView(R.layout.popup_new_lan);
		
		TextView lbserver = (TextView)dialog.findViewById(R.id.lbIPLan);
		TextView lbusername = (TextView)dialog.findViewById(R.id.lbusernameLAN);
		TextView lbpassword = (TextView)dialog.findViewById(R.id.lbpasswordLAN);
		
		lbserver.setText("IP Address");
		lbusername.setText(getString(R.string.username));
		lbpassword.setText(getString(R.string.password));
		
		EditText vlIp = (EditText)dialog.findViewById(R.id.vlIPLAN);
		EditText vlusername = (EditText)dialog.findViewById(R.id.vlUsernameLAN);
		EditText vlpassword = (EditText)dialog.findViewById(R.id.vlPasswordLAN);
		
		Button buttonSave = (Button)dialog.findViewById(R.id.btSaveLAN);
		Button buttonCancel = (Button)dialog.findViewById(R.id.btCancelLAN);
		
		buttonSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
			}
		});
		
		buttonCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				dialog.cancel();
			}
		});
		
		dialog.show();
		
	}
	// TODO process new folder item LAN
	public void processNewFolderItemLAN(){
		
	}
}
